from sqlalchemy import (
    Column,
    Integer,
    String,
    DateTime,
    PrimaryKeyConstraint,
    text, func,
)
from sqlalchemy.orm import relationship

from src.extension.extension_db import db
from src.model import Category, Exercise, StudentAnswer


class ExerciseUserMans(db.Model):
    """练习管理表模型"""
    __tablename__ = "exercise_user_mans"
    __table_args__ = (
        PrimaryKeyConstraint("id", name="pk_exercise_user_mans_id"),
    )

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255), nullable=False, server_default=text("''::character varying"))
    branch_id = Column(String(255), nullable=False, server_default=text("''::character varying"))
    user_id = Column(Integer, nullable=False)
    compile = Column(Integer, nullable=False)
    category_id = Column(Integer, nullable=False)
    updated_at = Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP(0)'),
                        server_onupdate=text('CURRENT_TIMESTAMP(0)'))
    exercises = relationship("ExerciseUser", backref="exercise_user_man")

    created_at = Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP(0)'))
    @property
    def getScore(self):
        return db.session.query(func.coalesce(func.sum(StudentAnswer.score), 0)).filter(StudentAnswer.branch_id==self.branch_id,StudentAnswer.user_id == self.user_id,StudentAnswer.is_correct==True).scalar()
    @property
    def getCateGory(self):
        return db.session.query(Category).filter(Category.id == self.category_id).first()
